/*
 * GYAsyncCmdFactory.cpp
 *
 *  Created on: 2015年9月22日
 *      Author: gaoyi
 */

#include "CTBase.h"

#include "GYAsyncCmdFactory.h"
#include "GYAsyncCmd.h"
#include "GYAsyncCmdRegister.h"

using namespace CTLib;

int GYAsyncCmdFactory::GetCmdSeq()
{
    if (m_iCmdSeq >= ENUM_GYASYNC_CMD_FACTORY_MAX_CMD || m_iCmdSeq < 0)
    {
        m_iCmdSeq = 0;
    }

    return ++m_iCmdSeq;
}

void GYAsyncCmdFactory::RegisterCmd(int iCmdId, GYAsyncCmdRegisterInf *p)
{
	std::map<int, GYAsyncCmdRegisterInf *>::iterator it = m_stCmdRegisterMap.begin();
	if (it != m_stCmdRegisterMap.end())
	{
		CT_THROW(("cmdId(%d) is exist", iCmdId));
		return;
	}
	CT_INFO(("register cmdId = %d sucess", iCmdId));
	m_stCmdRegisterMap[iCmdId] = p;
}

GYAsyncCmd*	GYAsyncCmdFactory::CreateCmd(int iCmdId)
{
	std::map<int, GYAsyncCmdRegisterInf *>::iterator it = m_stCmdRegisterMap.find(iCmdId);
	if (it != m_stCmdRegisterMap.end())
	{
		GYAsyncCmdRegisterInf* pCmdRegisterInf = it->second;
		GYAsyncCmd*	pAsyncCmd = pCmdRegisterInf->CreateObject();
		if (pAsyncCmd == NULL)
		{
			CT_ERROR(("createObject failed! cmdId = %d", iCmdId));
			return NULL;
		}

		pAsyncCmd->SetCmdId(iCmdId);

		int seq = GetCmdSeq();
		if (m_stCmdSeqMap.find(seq) == m_stCmdSeqMap.end())
		{
			pAsyncCmd->SetCmdSeq(seq);
		}
		else
		{
			CT_ERROR(("create cmd seq is exist!", seq));
			return NULL;
		}


		m_stCmdSeqMap.insert(std::make_pair(pAsyncCmd->GetCmdSeq(), pAsyncCmd));
		CT_TRACE(("create asyncCmd %d(%p)",pAsyncCmd->GetCmdId(), pAsyncCmd));
		return pAsyncCmd;
	}
	return NULL;
}

int GYAsyncCmdFactory::FreeCmd(GYAsyncCmd* pstCmd)
{
	if (pstCmd == NULL)
	{
		return -1;
	}

	if (m_stCmdSeqMap.find(pstCmd->GetCmdSeq()) == m_stCmdSeqMap.end())
	{
		return -1;
	}

	m_stCmdSeqMap.erase(pstCmd->GetCmdSeq());
	pstCmd->Release();
	return 0;
}
